package com.tsd.core.exception;

import com.tsd.core.utils.ExceptionUtil;
import com.tsd.core.vo.ErrorCode;
import com.tsd.core.vo.HttpResult;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.AuthorizationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName: ShiroExceptionHandler
 * @Description: TODO
 * @Author: Hillpool
 * @Date: 2022/7/18 15:10
 * @Version: 1.0
 */
@ControllerAdvice
@Order(value = Ordered.HIGHEST_PRECEDENCE)
public class ShiroExceptionHandler {

    public static final Logger LOGGER = LoggerFactory.getLogger(ShiroExceptionHandler.class);

    @ExceptionHandler(AuthenticationException.class)
    @ResponseBody
    public Object unauthenticatedHandler(HttpServletRequest request, AuthenticationException e) {
        LOGGER.error(ExceptionUtil.getStackTraceFromException(e));
        return HttpResult.fail(ErrorCode.CODE_NO_LOGINNED, "请登录");
    }

    @ExceptionHandler(AuthorizationException.class)
    @ResponseBody
    public Object unauthorizedHandler(HttpServletRequest request, AuthorizationException e) {
        LOGGER.error(ExceptionUtil.getStackTraceFromException(e));
        return HttpResult.fail(ErrorCode.CODE_PROC_ERROR, "无操作权限");
    }
}
